package com.xsr.blog.demo.javablacklistdesign.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author：xsr
 * @Date：2024/1/28 21:26
 * 加载黑名单内容，提供黑名单ip操作方法
 */
@Service
public class IpService {
    private final static Logger logger = LoggerFactory.getLogger(IpService.class);

    /**
     * 黑名单ip列表
     */
    private Set<String> blackIpList=new HashSet<>();

    /**
     * 构造函数中加载黑名单内容，并保存到blackIpList中。
     */
    public IpService() {
        ClassPathResource resource = new ClassPathResource("blackList.txt");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            String line;
            while ((line=reader.readLine())!=null){
                blackIpList.add(line);
            }
            logger.info("加载黑名单文件完成：共"+blackIpList.size()+"条ip被封锁");
            reader.close();
        } catch (IOException e) {
            logger.warn("加载黑名单文件失败");
            throw new RuntimeException(e);
        }
    }

    /**
     * 该ip是否在黑名单
     * @param ip
     * @return
     */
    public boolean isBlacklisted(String ip) {
        return blackIpList.contains(ip);
    }
}
